#!/usr/bin/env python3
"""
检查是否需要进入详情页面来获取完整的Key Features
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
import time
import json

def check_detail_page_access():
    """检查是否需要进入详情页面"""
    
    chrome_options = Options()
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--window-size=1920,1080')
    # chrome_options.add_argument('--headless')
    
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=chrome_options)
    
    try:
        print("🔍 检查是否需要进入详情页面来获取完整Key Features...")
        
        # 访问页面
        url = "https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2/model?catalogId=WAEGB-CGE-2022-FocusMCAGBR202450&series=ACMAA_VS-DH&planId=c"
        driver.get(url)
        
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, 'div[data-cy][class*="ProductTile"]'))
        )
        
        # 处理Cookie
        try:
            cookie_buttons = driver.find_elements(By.CSS_SELECTOR, 'button[id*="cookie"], button[class*="cookie"]')
            for btn in cookie_buttons:
                if btn.is_displayed():
                    btn.click()
                    time.sleep(1)
        except:
            pass
        
        # 找到Titanium车型
        titanium_element = driver.find_element(By.CSS_SELECTOR, 'div[data-cy="Titanium"]')
        print("✅ 找到Titanium车型")
        
        # 方法1: 查找直接进入详情页的链接
        print("\n🔍 方法1: 查找直接的详情页链接...")
        
        detail_link_selectors = [
            'a[class*="detail"]',
            'a[class*="more"]',
            'a[href*="detail"]',
            'a[href*="configure"]',
            'a[href*="build"]',
            'button[class*="configure"]',
            'button[class*="build"]',
            'button[class*="select"]'
        ]
        
        detail_links = []
        for selector in detail_link_selectors:
            try:
                links = titanium_element.find_elements(By.CSS_SELECTOR, selector)
                for link in links:
                    if link.is_displayed():
                        detail_links.append({
                            'element': link,
                            'selector': selector,
                            'text': link.text,
                            'href': link.get_attribute('href'),
                            'class': link.get_attribute('class')
                        })
            except:
                continue
        
        print(f"找到 {len(detail_links)} 个可能的详情页链接:")
        for i, link_info in enumerate(detail_links):
            print(f"  {i+1}. 选择器: {link_info['selector']}")
            print(f"     文本: '{link_info['text']}'")
            print(f"     href: {link_info['href']}")
            print(f"     class: {link_info['class']}")
        
        # 方法2: 点击View Specifications后查找详情链接
        print(f"\n🔍 方法2: 在模态框中查找详情链接...")
        
        try:
            # 点击View Specifications
            spec_button = titanium_element.find_element(By.CSS_SELECTOR, 'button[data-cy="product-tile-overlay"]')
            ActionChains(driver).move_to_element(titanium_element).perform()
            time.sleep(1)
            driver.execute_script("arguments[0].click();", spec_button)
            time.sleep(3)
            
            print("✅ 已打开规格模态框")
            
            # 在模态框中查找更多链接
            modal_link_selectors = [
                'a[class*="detail"]',
                'a[class*="more"]',
                'a[class*="learn"]',
                'a[href*="detail"]',
                'a[href*="configure"]',
                'a[href*="build"]',
                'button[class*="configure"]',
                'button[class*="build"]',
                'button[class*="select"]',
                'button[class*="choose"]',
                '*[class*="cta"]',
                '*[class*="primary"]'
            ]
            
            modal_links = []
            for selector in modal_link_selectors:
                try:
                    links = driver.find_elements(By.CSS_SELECTOR, selector)
                    for link in links:
                        if link.is_displayed():
                            modal_links.append({
                                'element': link,
                                'selector': selector,
                                'text': link.text,
                                'href': link.get_attribute('href'),
                                'class': link.get_attribute('class'),
                                'tag': link.tag_name
                            })
                except:
                    continue
            
            print(f"在模态框中找到 {len(modal_links)} 个可能的链接:")
            for i, link_info in enumerate(modal_links):
                print(f"  {i+1}. 选择器: {link_info['selector']}")
                print(f"     标签: {link_info['tag']}")
                print(f"     文本: '{link_info['text']}'")
                print(f"     href: {link_info['href']}")
                print(f"     class: {link_info['class']}")
            
            # 尝试点击最有希望的链接
            promising_links = []
            for link_info in modal_links:
                text = link_info['text'].lower()
                href = link_info['href'] or ''
                if any(keyword in text or keyword in href.lower() for keyword in ['configure', 'build', 'select', 'choose', 'detail']):
                    promising_links.append(link_info)
            
            print(f"\n🎯 找到 {len(promising_links)} 个有希望的链接:")
            
            for i, link_info in enumerate(promising_links):
                print(f"\n🖱️  尝试点击第 {i+1} 个链接: '{link_info['text']}'")
                
                try:
                    current_url = driver.current_url
                    link = link_info['element']
                    
                    if link_info['href']:
                        # 如果有href，直接导航
                        driver.get(link_info['href'])
                    else:
                        # 否则点击元素
                        driver.execute_script("arguments[0].click();", link)
                    
                    time.sleep(5)
                    new_url = driver.current_url
                    
                    if new_url != current_url:
                        print(f"✅ 成功导航到新页面: {new_url}")
                        
                        # 在新页面中查找Key Features
                        print("🔍 在新页面中查找Key Features...")
                        
                        try:
                            # 等待页面加载
                            time.sleep(5)
                            
                            # 查找Key Features
                            key_feature_elements = driver.find_elements(By.XPATH, "//*[contains(text(), 'Key Features')]")
                            if key_feature_elements:
                                print(f"✅ 在新页面找到 {len(key_feature_elements)} 个Key Features部分")
                                
                                # 获取第一个Key Features部分的内容
                                first_kf = key_feature_elements[0]
                                try:
                                    parent = first_kf.find_element(By.XPATH, "../..")
                                    lis = parent.find_elements(By.CSS_SELECTOR, "li")
                                    
                                    print(f"新页面Key Features数量: {len(lis)}")
                                    
                                    features = []
                                    for li in lis:
                                        text = li.text.strip()
                                        if text and len(text) > 3:
                                            features.append(text)
                                    
                                    print(f"有效特性数量: {len(features)}")
                                    if features:
                                        print("前10个特性:")
                                        for j, feature in enumerate(features[:10]):
                                            print(f"  {j+1}. {feature}")
                                    
                                    # 如果找到更多特性，保存结果
                                    if len(features) > 6:
                                        print(f"🎉 找到更完整的Key Features列表！")
                                        
                                        result = {
                                            'success': True,
                                            'method': 'detail_page_navigation',
                                            'link_text': link_info['text'],
                                            'link_href': link_info['href'],
                                            'new_url': new_url,
                                            'features_count': len(features),
                                            'features': features
                                        }
                                        
                                        with open('./release/detail_page_success.json', 'w', encoding='utf-8') as f:
                                            json.dump(result, f, ensure_ascii=False, indent=2)
                                        
                                        print("💾 成功结果已保存到 ./release/detail_page_success.json")
                                        return result
                                    
                                except Exception as e:
                                    print(f"解析新页面Key Features失败: {e}")
                            else:
                                print("❌ 新页面中未找到Key Features")
                        
                        except Exception as e:
                            print(f"分析新页面失败: {e}")
                        
                        # 返回原页面继续测试
                        driver.get(current_url)
                        time.sleep(3)
                        
                        # 重新打开模态框
                        titanium_element = driver.find_element(By.CSS_SELECTOR, 'div[data-cy="Titanium"]')
                        spec_button = titanium_element.find_element(By.CSS_SELECTOR, 'button[data-cy="product-tile-overlay"]')
                        ActionChains(driver).move_to_element(titanium_element).perform()
                        time.sleep(1)
                        driver.execute_script("arguments[0].click();", spec_button)
                        time.sleep(3)
                        
                    else:
                        print(f"❌ 点击后URL未改变")
                        
                except Exception as e:
                    print(f"❌ 点击链接失败: {e}")
        
        except Exception as e:
            print(f"❌ 打开模态框失败: {e}")
        
        print(f"\n📊 总结:")
        print(f"  当前获取的Key Features数量: 5-6个")
        print(f"  期望的Key Features数量: 17个") 
        print(f"  缺少的Key Features数量: 约12个")
        print(f"  结论: 需要找到其他方式获取完整的Key Features列表")
        
    except Exception as e:
        print(f"❌ 检查过程中出现异常: {e}")
        import traceback
        traceback.print_exc()
        
    finally:
        print("🧹 清理资源...")
        driver.quit()

if __name__ == "__main__":
    check_detail_page_access()
